import {
    View, FlatList, RefreshControl, TouchableOpacity, AsyncStorage,
    TouchableHighlight, Text, StyleSheet, Image, Alert, DatePickerAndroid
} from 'react-native';
import React, {PureComponent} from 'react';
import Urls, {getRealUrl} from '../const/Urls'
import LocalImg from '../const/Images'
import moment from 'moment'

/*
 * 引航员工分
 */
class PageYhygf extends PureComponent {

    constructor(props) {
        super(props);
        let date = new Date();
        date.setTime(date.getTime() - 24 * 60 * 60 * 1000 * 30);
        this.state = {
            user: {
                token: '',
                pilotCode: '',
                pilotName: '',
                bmbm: '',
            },
            data: [],
            isLoading: false,
            startDate: date,
            total: 0,
            times: 0,
            endDate: new Date(),
        };
        this.setUser();
    }

    componentDidMount() {
        this.setState({
            data: [],
        });
        this.setUser();
    }

    setUser() {
        AsyncStorage.getItem("user", (error, result) => {
            if (!error) {

                const data = JSON.parse(result);
                if (data) {
                    this.setState({
                        user: {
                            token: data['token'],
                            pilotCode: data['pilotCode'],
                            pilotName: data['pilotName'],
                            bmbm: data['bmbm']
                        }
                    });
                    this.loadData();
                } else {
                    this.setState({
                        user: {
                            token: '',
                            pilotCode: '',
                            pilotName: '',
                            bmbm: ''
                        }
                    });
                }
            }
        })
    }

    render() {
        return (
            <View style={{flexDirection: 'column', flex: 1}}>

                <View style={{
                    flexDirection: 'row',
                    flex: 0,
                    height: 60,
                    alignItems: 'center',
                    justifyContent: 'center',
                    backgroundColor: '#0066FF'
                }}>
                    <View style={{flex: 1, padding: 10}}>
                        <TouchableOpacity onPress={() => this.props.navigation.pop()}>
                            <Image source={LocalImg['backImg']} style={{height: 30, width: 30, resizeMode: 'contain'}}/>
                        </TouchableOpacity>
                    </View>
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                        <Text style={{fontSize: 20, color: '#ffffff'}}>引航员工分</Text>
                    </View>

                    <View style={{flex: 1, alignItems: 'flex-end', padding: 10}}>

                    </View>
                </View>


                <View style={{flexDirection: 'column'}}>
                    <View style={{flexDirection: 'row', margin: 10, alignItems: 'center'}}>
                        <View>
                            <Text style={{fontSize: 18}}>日期</Text>
                        </View>

                        <TouchableOpacity onPress={() => this.selectStartDate()} style={{flex: 1}}>
                            <View style={{
                                flex: 1,
                                flexDirection: 'row',
                                borderBottomWidth: 1,
                                borderColor: '#000000'
                            }}>
                                <Text style={{
                                    textAlign: 'center',
                                    flex: 1,
                                    width: 100
                                }}>{this.getFormatDate(this.state.startDate)}</Text>
                            </View>
                        </TouchableOpacity>

                        <View>
                            <Text style={{fontSize: 18}}>~</Text>
                        </View>

                        <TouchableOpacity onPress={() => this.selectEndDate()} style={{flex: 1}}>
                            <View style={{
                                flex: 1,
                                flexDirection: 'row',
                                borderBottomWidth: 1,
                                borderColor: '#000000'
                            }}>
                                <Text style={{
                                    textAlign: 'center',
                                    flex: 1,
                                    width: 100
                                }}>{this.getFormatDate(this.state.endDate)}</Text>
                            </View>
                        </TouchableOpacity>

                        <View>
                            <TouchableHighlight onPress={() => this.search()}>
                                <Text style={{fontSize: 18}}>查询</Text>
                            </TouchableHighlight>
                        </View>
                    </View>
                    <View style={{flexDirection: 'row', justifyContent: 'center'}}>
                        <View style={{flex: 1}}>
                            <Text style={{textAlign: 'center'}}>工分总计:{this.state.total}</Text>
                        </View>
                        <View style={{flex: 1}}>
                            <Text style={{textAlign: 'center'}}>艘次总计:{this.state.times}</Text>
                        </View>
                    </View>
                </View>

                <View style={{height: 1, backgroundColor: '#CCCCCC'}}/>

                <FlatList
                    data={this.state.data}
                    renderItem={(item, index) => this.renderRow(item, index)}
                    keyExtractor={this.keyExtractor}
                    ItemSeparatorComponent={this.separator}
                    ListFooterComponent={() => this.footerView()}
                    onEndReachedThreshold={0.1}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isLoading}
                            onRefresh={() => this.onRefresh()}
                        />
                    }/>

            </View>
        )
    }

    keyExtractor = (item, index) => item.YHYID + "";

    footerView() {
        return (
            <View style={{flexDirection: 'row', justifyContent: 'center', paddingTop: 20, paddingBottom: 30}}>
                <Text>到底了</Text>
            </View>
        )
    }


    onRefresh() {
        this.setState({
            data: [],
        });
        this.loadData();
    }


    loadData() {
        this.setState({
            data: [],
            isLoading: true
        });

        const request = new Map();
        request.set('qsdate', this.getFormatDate(this.state.startDate));
        request.set('jsdate', this.getFormatDate(this.state.endDate));
        request.set('yhycode', this.state.user.pilotCode);

        fetch(getRealUrl(Urls['yhygfUrl'], request), {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
        })
            .then(response => response.json())
            .then(responseJson => {
                if (responseJson instanceof Array) {
                    this.setState({
                        data: responseJson,
                        times: responseJson.length,
                    });
                    let total = 0;
                    responseJson.forEach(s => total = total + parseInt(s.ZGF));
                    this.setState({
                        total: total,
                        isLoading: false,
                    })
                } else {
                    this.setState({
                        data: [],
                        isLoading: false,
                    });
                }
            })
            .catch(error => {
                console.error(error);
                this.setState({
                    data: [],
                    isLoading: false
                });
            });


    }

    separator(index) {
        return (
            <View key={index} style={{height: 1, backgroundColor: '#CCCCCC'}}/>
        )
    }

    processDateTime(date) {
        const m = moment(date);
        if (m.isValid()) {
            return m.format('DD/HHmm')
        } else
            return ""
    }


    getFormatDate(date) {
        const m = moment(date);
        if (m.isValid()) {
            return m.format('YYYY-MM-DD')
        } else
            return ""
    }


    renderRow({item, index}) {

        let bColor = index % 2 !== 0 ? "#f9f9f9" : "#ffffff";
        let show = item.YHYID === '';
        let style = 'flex';
        if (show) {
            style = 'none'
        }
        return (

            <TouchableHighlight key={item.YHYID} style={{display: style}}>
                <View style={{
                    flexDirection: 'row',
                    padding: 10,
                    backgroundColor: bColor,
                    justifyContent: 'center',
                    alignItems: 'center',
                }}>


                    <View style={{marginLeft: 5, marginTop: 10}}>
                        <Text style={{color: '#0066FF'}}>{index + 1}.</Text>
                    </View>
                    <View style={[styles.text, {flex: 1, marginLeft: 10, marginTop: 10, justifyContent: 'center'}]}>
                        <View style={{flexDirection: 'row'}}>
                            <Text style={[styles.text, {fontWeight: 'bold'}]}>
                                船名：{item.SHIPNAME}
                            </Text>
                            <Text style={styles.text}>
                                工分：{item.ZGF}
                            </Text>
                        </View>

                        <View style={{flexDirection: 'row'}}>
                            <Text style={styles.text}>
                                开始时间：{this.processDateTime(item.QSDATE)}
                            </Text>
                            <Text style={styles.text}>
                                结束时间：{this.processDateTime(item.JSDATE)}
                            </Text>
                        </View>

                        <View style={{flexDirection: 'row'}}>
                            <Text style={styles.text}>
                                开始地点：{item.QSPLACE}
                            </Text>
                            <Text style={styles.text}>
                                结束地点：{item.JSPLACE}
                            </Text>
                        </View>
                    </View>


                </View>
            </TouchableHighlight>

        )
    }


    search() {
        this.setState({
            data: [],
        });
        this.loadData();
    }

    async selectStartDate() {
        try {
            const {action, year, month, day} = await DatePickerAndroid.open({
                date: this.state.startDate
            });
            if (action !== DatePickerAndroid.dismissedAction) {
                // 这里开始可以处理用户选好的年月日三个参数：year, month (0-11), day
                this.setState({
                    startDate: new Date(year, month, day),
                })
            }
        } catch ({code, message}) {
            console.warn('Cannot open date picker', message);
        }
    }


    async selectEndDate() {
        try {
            const {action, year, month, day} = await DatePickerAndroid.open({
                date: this.state.endDate
            });
            if (action !== DatePickerAndroid.dismissedAction) {
                // 这里开始可以处理用户选好的年月日三个参数：year, month (0-11), day
                this.setState({
                    endDate: new Date(year, month, day),
                })
            }
        } catch ({code, message}) {
            console.warn('Cannot open date picker', message);
        }
    }


}

const styles = StyleSheet.create({
    phone: {
        flex: 1,
        textDecorationLine: 'underline',
        color: '#0066FF',
    },
    text: {
        flex: 1
    },
    row: {
        flexDirection: 'column',
        justifyContent: 'center',
        padding: 10,
    },
});


export default PageYhygf;